import { Module } from 'vuex'
import { IloginState } from './types'
import { IRootState } from '../types'
import router from '@/router'
import { mapMenusToRoutes } from '@/utils/map-menus'
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/service/login/login'
import localCache from '@/utils/cache'
const loginModule: Module<IloginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      const routes = mapMenusToRoutes(userMenus)
      //将routes 添加到router.main.children中
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
    }
  },
  actions: {
    async accountLoginAction({ commit }, payload: any) {
      //1.请求用户id和token
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit('changeToken', token)
      localCache.setCache('token', token)
      //2.请求用户信息
      const userInfo = await requestUserInfoById(id)
      commit('changeUserInfo', userInfo.data)
      localCache.setCache('userInfo', userInfo.data)

      //3.请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(
        userInfo.data.role.id
      )
      commit('changeUserMenus', userMenusResult.data)
      localCache.setCache('userMenu', userMenusResult.data)
      //4.跳到首页
      router.push('/main')
    },
    loadLocalLogin({ commit }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('changeToken', token)
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenu = localCache.getCache('userMenu')
      if (userMenu) {
        commit('changeUserMenus', userMenu)
      }
    }
  }
}

export default loginModule
